//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package awsmanager;

import com.awsmanager.common.AWSObjectUtils;
import com.awsmanager.common.EC2SecurityGroupDataProvider;
import com.awsmanager.utils.ProcessText;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Alert;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.Label;
import com.sun.webui.jsf.component.RadioButtonGroup;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import com.sun.webui.jsf.model.SingleSelectOptionsList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.ValidatorException;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version EC2AddIpPermission.java
 * @version Created on Nov 29, 2008, 12:24:35 PM
 * @author Sean ODell
 */
public class EC2AddIpPermission extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        rbg_HostTypeDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("host", "Host"), new com.sun.webui.jsf.model.Option("network", "Network")});
        rbg_HostTypeDefaultOptions.setSelectedValue("host");
        ddl_TypeDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("22", "SSH"), new com.sun.webui.jsf.model.Option("3389", "RDP"), new com.sun.webui.jsf.model.Option("80", "HTTP"), new com.sun.webui.jsf.model.Option("443", "HTTPS"), new com.sun.webui.jsf.model.Option("110", "POP3"), new com.sun.webui.jsf.model.Option("143", "IMAP"), new com.sun.webui.jsf.model.Option("995", "Secure POP3"), new com.sun.webui.jsf.model.Option("993", "Secure IMAP"), new com.sun.webui.jsf.model.Option("53", "DNS"), new com.sun.webui.jsf.model.Option("25", "SMTP"), new com.sun.webui.jsf.model.Option("465", "SMTPS"), new com.sun.webui.jsf.model.Option("3306", "MySQL"), new com.sun.webui.jsf.model.Option("1433", "MS SQL Server"), new com.sun.webui.jsf.model.Option("389", "LDAP"), new com.sun.webui.jsf.model.Option("other", "Other")});
        ddl_ProtocolDefaultOptions.setOptions(new com.sun.webui.jsf.model.Option[]{new com.sun.webui.jsf.model.Option("tcp", "TCP/IP"), new com.sun.webui.jsf.model.Option("udp", "UDP/IP")});
        ddl_TypeDefaultOptions.setSelectedValue("22");
    }
    private DropDown ddl_SecurityGroup = new DropDown();

    public DropDown getDdl_SecurityGroup() {
        return ddl_SecurityGroup;
    }

    public void setDdl_SecurityGroup(DropDown dd) {
        this.ddl_SecurityGroup = dd;
    }
    private SingleSelectOptionsList ddl_TypeDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDdl_TypeDefaultOptions() {
        return ddl_TypeDefaultOptions;
    }

    public void setDdl_TypeDefaultOptions(SingleSelectOptionsList ssol) {
        this.ddl_TypeDefaultOptions = ssol;
    }
    private DropDown ddl_Type = new DropDown();

    public DropDown getDdl_Type() {
        return ddl_Type;
    }

    public void setDdl_Type(DropDown dd) {
        this.ddl_Type = dd;
    }
    private TextField tf_Port = new TextField();

    public TextField getTf_Port() {
        return tf_Port;
    }

    public void setTf_Port(TextField tf) {
        this.tf_Port = tf;
    }
    private SingleSelectOptionsList rbg_HostTypeDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getRbg_HostTypeDefaultOptions() {
        return rbg_HostTypeDefaultOptions;
    }

    public void setRbg_HostTypeDefaultOptions(SingleSelectOptionsList ssol) {
        this.rbg_HostTypeDefaultOptions = ssol;
    }
    private RadioButtonGroup rbg_HostType = new RadioButtonGroup();

    public RadioButtonGroup getRbg_HostType() {
        return rbg_HostType;
    }

    public void setRbg_HostType(RadioButtonGroup rbg) {
        this.rbg_HostType = rbg;
    }
    private TextField tf_Network = new TextField();

    public TextField getTf_Network() {
        return tf_Network;
    }

    public void setTf_Network(TextField tf) {
        this.tf_Network = tf;
    }
    private TextField tf_Host = new TextField();

    public TextField getTf_Host() {
        return tf_Host;
    }

    public void setTf_Host(TextField tf) {
        this.tf_Host = tf;
    }
    private SingleSelectOptionsList ddl_ProtocolDefaultOptions = new SingleSelectOptionsList();

    public SingleSelectOptionsList getDdl_ProtocolDefaultOptions() {
        return ddl_ProtocolDefaultOptions;
    }

    public void setDdl_ProtocolDefaultOptions(SingleSelectOptionsList ssol) {
        this.ddl_ProtocolDefaultOptions = ssol;
    }
    private Label l_Port = new Label();

    public Label getL_Port() {
        return l_Port;
    }

    public void setL_Port(Label l) {
        this.l_Port = l;
    }
    protected boolean portVisible = true;

    /**
     * Get the value of portVisible
     *
     * @return the value of portVisible
     */
    public boolean isPortVisible() {
        return portVisible;
    }

    /**
     * Set the value of portVisible
     *
     * @param portVisible new value of portVisible
     */
    public void setPortVisible(boolean portVisible) {
        this.portVisible = portVisible;
    }
    protected boolean portRangeVisible = false;

    /**
     * Get the value of portRangeVisible
     *
     * @return the value of portRangeVisible
     */
    public boolean isPortRangeVisible() {
        return portRangeVisible;
    }

    /**
     * Set the value of portRangeVisible
     *
     * @param portRangeVisible new value of portRangeVisible
     */
    public void setPortRangeVisible(boolean portRangeVisible) {
        this.portRangeVisible = portRangeVisible;
    }
    private TextField tf_PortRangeFrom = new TextField();

    public TextField getTf_PortRangeFrom() {
        return tf_PortRangeFrom;
    }

    public void setTf_PortRangeFrom(TextField tf) {
        this.tf_PortRangeFrom = tf;
    }
    private TextField tf_PortRangeTo = new TextField();

    public TextField getTf_PortRangeTo() {
        return tf_PortRangeTo;
    }

    public void setTf_PortRangeTo(TextField tf) {
        this.tf_PortRangeTo = tf;
    }
    private DropDown ddl_Protocol = new DropDown();

    public DropDown getDdl_Protocol() {
        return ddl_Protocol;
    }

    public void setDdl_Protocol(DropDown dd) {
        this.ddl_Protocol = dd;
    }
    private Alert al_EC2AddIpPerm = new Alert();

    public Alert getAl_EC2AddIpPerm() {
        return al_EC2AddIpPerm;
    }

    public void setAl_EC2AddIpPerm(Alert a) {
        this.al_EC2AddIpPerm = a;
    }
    protected Option[] securityGroupsNameOptions;

    public Option[] getSecurityGroupsNameOptions() {
        return securityGroupsNameOptions;
    }

    public void setSecurityGroupsNameOptions(Option[] securityGroupsNameOptions) {
        this.securityGroupsNameOptions = securityGroupsNameOptions;
    }
    protected boolean initSecurityGroupList = true;

    public boolean isInitSecurityGroupList() {
        return initSecurityGroupList;
    }

    public void setInitSecurityGroupList(boolean initSecurityGroupList) {
        this.initSecurityGroupList = initSecurityGroupList;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public EC2AddIpPermission() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("EC2AddIpPermission Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here

        if (this.isInitSecurityGroupList()) {
            Map ec2SecurityGroupsInfo = new HashMap();

            ArrayList ec2SecurityGroupsNamesList = new ArrayList();
            ec2SecurityGroupsInfo = getSessionBean1().getEc2SecurityGroupsInfo();
            ec2SecurityGroupsNamesList = (ArrayList) ec2SecurityGroupsInfo.get("selectednames");

            Option[] ec2SecurityGroupsOptions = new Option[ec2SecurityGroupsNamesList.size()];
            for (int i = 0; i < ec2SecurityGroupsNamesList.size(); i++) {
                ec2SecurityGroupsOptions[i] = new Option(ec2SecurityGroupsNamesList.get(i));
            }
            setSecurityGroupsNameOptions(ec2SecurityGroupsOptions);
            this.setInitSecurityGroupList(false);
        }
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public void ddl_Type_processValueChange(ValueChangeEvent event) {
        if (!ddl_Type.getSelected().equals("other")) {
            tf_Port.setText(ddl_Type.getSelected());
            setPortVisible(true);
            setPortRangeVisible(false);
        } else {
            setPortVisible(false);
            setPortRangeVisible(true);
        }
    }

    public String addIpPermissionExternalBtn_action() {

        Map statusMsg = new HashMap();
        Map ipPermissionInfo = new HashMap();
        al_EC2AddIpPerm.setSummary("");
        al_EC2AddIpPerm.setDetail("");

        AWSObjectUtils awsObjectUtils = new AWSObjectUtils();
        String securitygroup =
                awsObjectUtils.idExtract((String) ddl_SecurityGroup.getSelected());

        String securityregion =
                awsObjectUtils.nameExtract((String) ddl_SecurityGroup.getSelected());

        ipPermissionInfo.put("securitygroup", securitygroup);
        ipPermissionInfo.put("securityregion", securityregion);
        ipPermissionInfo.put("protocol", ddl_Protocol.getSelected());

        if (!ddl_Type.getSelected().equals("other")) {
            try {
                Integer.parseInt((String) tf_Port.getText());
            } catch (NumberFormatException ex) {
                al_EC2AddIpPerm.setSummary("Port numbers must be integers in the range 0 to 65,535.");
                return null;
            }
            ipPermissionInfo.put("fromPort", tf_Port.getText());
            ipPermissionInfo.put("toPort", tf_Port.getText());
        } else {
            try {
                Integer.parseInt((String) tf_PortRangeFrom.getText());
                Integer.parseInt((String) tf_PortRangeTo.getText());
            } catch (NumberFormatException ex) {
                al_EC2AddIpPerm.setSummary("Port numbers must be integers in the range 0 to 65,535.");
                return null;
            }
            ipPermissionInfo.put("fromPort", tf_PortRangeFrom.getText());
            ipPermissionInfo.put("toPort", tf_PortRangeTo.getText());
        }

        if (rbg_HostType.getSelected().equals("host")) {
            if (tf_Host.getText() == null) {
                al_EC2AddIpPerm.setSummary("Host is checked, but no address is entered.");
                return null;
            } else {
                if (tf_Host.getText().toString().indexOf("/") < 0) {
                    ipPermissionInfo.put("cidrip", (String) tf_Host.getText() + "/32");
                } else {
                    ipPermissionInfo.put("cidrip", tf_Host.getText());
                }
            }
        } else {
            if (tf_Network.getText() == null) {
                al_EC2AddIpPerm.setSummary("Network is checked, but no address is entered.");
                return null;
            } else {
                ipPermissionInfo.put("cidrip", tf_Network.getText());
            }
        }

        statusMsg = getSessionBean1().getEc2IpPermissionDataProvider().addIpPermissionExternal(
                getSessionBean1().getEc2Connection(),
                ipPermissionInfo);

        if (statusMsg.get("type") != null) {
            al_EC2AddIpPerm.setSummary((String) statusMsg.get("msg"));
            al_EC2AddIpPerm.setType((String) statusMsg.get("type"));
        }

        return null;
    }

    public void tf_Host_validate(FacesContext context, UIComponent component, Object value) {
        ProcessText processtext = new ProcessText();
        String str = String.valueOf(value);

        if (rbg_HostType.getSelected().equals("host")) {
            if (!processtext.validCIDRIp(str, "host")) {
                al_EC2AddIpPerm.setSummary("Malformed CIDR.");
                al_EC2AddIpPerm.setDetail("Expecting valid IP address in the format: n.n.n.n/n or n.n.n.n");
                throw new ValidatorException(new FacesMessage("Not a valid CIDR."));
            } else {
                al_EC2AddIpPerm.setSummary("");
                al_EC2AddIpPerm.setDetail("");
            }
        }
    }

    public void tf_Network_validate(FacesContext context, UIComponent component, Object value) {
        ProcessText processtext = new ProcessText();
        String str = String.valueOf(value);

        if (rbg_HostType.getSelected().equals("network")) {
            if (!processtext.validCIDRIp(str, "network")) {
                al_EC2AddIpPerm.setSummary("Malformed CIDR.");
                al_EC2AddIpPerm.setDetail("Expecting valid IP address in the format: n.n.n.n/n");
                throw new ValidatorException(new FacesMessage("Malformed CIDR."));
            } else {
                al_EC2AddIpPerm.setSummary("");
                al_EC2AddIpPerm.setDetail("");
            }
        }
    }

    public String tab_External_action() {
        return null;
    }

    public String returnSGExternalPermBtn_action() {
        getSessionBean1().getEc2SecurityGroupDataProvider().load(getSessionBean1().getEc2Connection());
        EC2SecurityGroupDataProvider ec2SecurityGroupDataProvider =
                getSessionBean1().getEc2SecurityGroupDataProvider();
        Map ec2SecurityGroupsInfo = getSessionBean1().getEc2SecurityGroupsInfo();
        getSessionBean1().getEc2IpPermissionDataProvider().load(ec2SecurityGroupsInfo,
                ec2SecurityGroupDataProvider);
        return "return";
    }

    public String tab_Group_action() {
        return null;
    }
}